package com.canxi.earn.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.canxi.common.core.page.TableDataInfo;
import com.canxi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.canxi.common.utils.redis.RedisUtils;
import com.canxi.cxcommon.config.CanxiConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.canxi.earn.domain.bo.CxJokeBo;
import com.canxi.earn.domain.vo.CxJokeVo;
import com.canxi.earn.domain.CxJoke;
import com.canxi.earn.mapper.CxJokeMapper;
import com.canxi.earn.service.ICxJokeService;

import java.util.*;

import com.canxi.cxcommon.utils.PageUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.hutool.core.util.StrUtil;
import icu.mhb.mybatisplus.plugln.base.service.impl.JoinServiceImpl;
import icu.mhb.mybatisplus.plugln.core.JoinLambdaWrapper;

import static com.canxi.cxcommon.enums.CXJokeSourceEnum.聚合数据;

/**
 * 笑话Service业务层处理
 *
 * @author ruoyi
 * @date 2024-09-05
 */
@RequiredArgsConstructor
@Service
public class CxJokeServiceImpl  extends JoinServiceImpl<CxJokeMapper, CxJoke>  implements ICxJokeService {

    private final CxJokeMapper baseMapper;

    @Override
    public TableDataInfo<CxJokeVo> queryCxJokeList(CxJokeBo cxJokeBo) {
        TableDataInfo<CxJokeVo> dataInfo = PageUtils.buildDataInfo(this.baseMapper.queryCxJokeList(PageUtils.buildPage(), BeanUtil.toBean(cxJokeBo, CxJokeVo.class)));
        return dataInfo;
    }

    @Override
    public List<CxJokeVo> queryCxJokeAll(CxJokeBo cxJokeBo) {
        return this.baseMapper.queryCxJokeList(BeanUtil.toBean(cxJokeBo, CxJokeVo.class));
    }



    /**
     * 查询笑话
     */
    @Override
    public CxJokeVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询笑话列表
     */
    @Override
    public List<CxJokeVo> queryList(CxJokeBo bo) {
        JoinLambdaWrapper<CxJoke> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private JoinLambdaWrapper<CxJoke> buildQueryWrapper(CxJokeBo bo) {
        Map<String, Object> params = bo.getParams();
        JoinLambdaWrapper<CxJoke> lqw = joinLambdaQueryWrapper();
        lqw.eq(StrUtil.isNotBlank(bo.getTitle()), CxJoke::getTitle, bo.getTitle());
        lqw.eq(StrUtil.isNotBlank(bo.getContent()), CxJoke::getContent, bo.getContent());
        lqw.eq(StrUtil.isNotBlank(bo.getSourceType()), CxJoke::getSourceType, bo.getSourceType());
        lqw.eq(StrUtil.isNotBlank(bo.getSourceId()), CxJoke::getSourceId, bo.getSourceId());
        lqw.eq(StrUtil.isNotBlank(bo.getCategoryId()), CxJoke::getCategoryId, bo.getCategoryId());
        lqw.eq(StrUtil.isNotBlank(bo.getStatus()), CxJoke::getStatus, bo.getStatus());
        lqw.eq(bo.getSort() != null, CxJoke::getSort, bo.getSort());
        return lqw;
    }

    /**
     * 新增笑话
     */
    @Override
    public Boolean insertByBo(CxJokeBo bo) {
        CxJoke add = BeanUtil.toBean(bo, CxJoke.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改笑话
     */
    @Override
    public Boolean updateByBo(CxJokeBo bo) {
        CxJoke update = BeanUtil.toBean(bo, CxJoke.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(CxJoke entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除笑话
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Boolean addFromOther(CxJokeBo bo) {

        int page = 1;
        Object jokePage = RedisUtils.getCacheObject("juhe_joke_page");
        if(ObjectUtil.isNotNull(jokePage)){
            page = Integer.valueOf((Integer) jokePage)+1;
        }



        String apiKey = CanxiConfig.getJuheApi();
        String apiUrl = "http://v.juhe.cn/joke/content/list.php";

        HashMap<String, Object> map = new HashMap<>();
        map.put("key", apiKey);
        map.put("sort", "desc");
        map.put("page", page);
        map.put("pagesize", "100");
        map.put("time", System.currentTimeMillis()/1000+"");

        String s = HttpUtil.get(apiUrl, map);
        JSONObject object = JSONUtil.parseObj(s);

        if(!StrUtil.equals(object.get("error_code").toString(), "0")){
            throw new SecurityException(object.get("reason").toString());
        }
        JSONObject result = (JSONObject) object.get("result");
        JSONArray array = (JSONArray) result.get("data");

        ArrayList<CxJoke> bos = new ArrayList<>();
        for (int i = 0; i < array.size(); i++) {
            Map<String, Object> v = (Map<String, Object>) array.get(i);
            CxJoke bo1 = new CxJoke();
            bo1.setSourceId(v.get("hashId").toString());
            bo1.setContent(v.get("content").toString());
            bo1.setSourceType(聚合数据.getCode());
            bos.add(bo1);

        }

        boolean b = this.baseMapper.insertOrUpdateBatch(bos);
        RedisUtils.setCacheObject("juhe_joke_page", page);
        return b;
    }

    @Override
    public CxJokeVo queryRandomInfo() {
        return baseMapper.queryRandomInfo();
    }
}
